package com.omesoft.hksnore.util.photo;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.HashMap;

public class MyFileUtils {
	public static final HashMap<String, String> mFileTypes = new HashMap<String, String>();
	static {
		// images
		mFileTypes.put("FFD8FF", "jpg");
		mFileTypes.put("89504E", "png");
		mFileTypes.put("474946", "gif");
		mFileTypes.put("49492A", "tif");
		mFileTypes.put("424D36", "bmp");
		//
		mFileTypes.put("414331", "dwg"); // CAD
		mFileTypes.put("384250", "psd");
		mFileTypes.put("7B5C72", "rtf"); // 日记本
		mFileTypes.put("3C3F78", "xml");
		mFileTypes.put("68746D", "html");
		mFileTypes.put("44656C", "eml"); // 邮件
		mFileTypes.put("D0CF11", "doc");
		mFileTypes.put("537461", "mdb");
		mFileTypes.put("252150", "ps");
		mFileTypes.put("255044", "pdf");
		mFileTypes.put("504B03", "zip");
		mFileTypes.put("526172", "rar");
		mFileTypes.put("574156", "wav");
		mFileTypes.put("415649", "avi");
		mFileTypes.put("2E524D", "rm");
		mFileTypes.put("000001", "mpg");
		mFileTypes.put("000001", "mpg");
		mFileTypes.put("6D6F6F", "mov");
		mFileTypes.put("3026B2", "asf");
		mFileTypes.put("4D5468", "mid");
	}

	// 复制文件
	public static void copyFile(File sourceFile, File targetFile) {
		BufferedInputStream inBuff = null;
		BufferedOutputStream outBuff = null;
		try {
			// 新建文件输入流并对它进行缓冲
			inBuff = new BufferedInputStream(new FileInputStream(sourceFile));

			// 新建文件输出流并对它进行缓冲
			outBuff = new BufferedOutputStream(new FileOutputStream(targetFile));

			// 缓冲数组
			byte[] b = new byte[1024 * 5];
			int len;
			while ((len = inBuff.read(b)) != -1) {
				outBuff.write(b, 0, len);
			}
			// 刷新此缓冲的输出流
			outBuff.flush();
		} catch (Exception e) {
			// Log.e("test","copyFile_e.getMessage():"+e.getMessage());
		} finally {
			try {
				// 关闭流
				if (inBuff != null)
					inBuff.close();
				if (outBuff != null)
					outBuff.close();
			} catch (Exception e2) {
				// Log.e("test","copyFile_e2.getMessage():"+e2.getMessage());
			}
		}
	}

	public static String bytesToHexString(byte[] src) {
		StringBuilder stringBuilder = new StringBuilder();
		if (src == null || src.length <= 0) {
			return null;
		}
		for (int i = 0; i < src.length; i++) {
			int v = src[i] & 0xFF;
			String hv = Integer.toHexString(v);
			if (hv.length() < 2) {
				stringBuilder.append(0);
			}
			stringBuilder.append(hv);
		}
		return stringBuilder.toString();
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String[] demandFileTypes = { "jpg", "png", "zip" };
		File file = new File("D:\\win8_64_MyDrivers.zip");
		boolean isPicType = isFitFileType(demandFileTypes, file);
		// System.out.println(isPicType);
	}

	/** 是否符合要求的文件类型 */
	public static boolean isFitFileType(String[] demandFileTypes, File file) {
		boolean isPicType = false;
		String fileType = getFileType(file);
		for (String targetFileType : demandFileTypes) {
			if (targetFileType.equalsIgnoreCase(fileType)) {
				isPicType = isPicType || true;
			} else {
				isPicType = isPicType || false;
			}
		}
		return isPicType;
	}

	private static String getFileType(File file) {
		String fileType = null;
		FileInputStream is = null;
		try {
			is = new FileInputStream(file);
			byte[] b = new byte[20];
			is.read(b, 0, b.length);
			String key = bytesToHexString(b).substring(0, 6).toUpperCase();
			fileType = mFileTypes.get(key);
		} catch (Exception e) {
			// System.out.println("getFileType_e.getMessage():"+e.getMessage());
		} finally {
			try {
				if (is != null) {
					is.close();
				}
			} catch (Exception e2) {
				// System.out.println("getFileType_e2.getMessage():"+e2.getMessage());
			}
		}
		return fileType;
	}

	/** 裁剪方法 */
	public static void showPicToCutPhoto(Uri uri, Activity activity) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		// 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
		intent.putExtra("crop", "true");
		// System.out.println("activityName:"+activity.getClass());
		int aspectY = (int) (MyPixelConvertUtil.getScreenHeight(activity) / MyPixelConvertUtil.getScreenWidth(activity));
		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", aspectY);
		// 这里裁剪图片宽高不能乘积不能大于255的平方
		intent.putExtra("outputX", 200);
		intent.putExtra("outputY", 200);
		intent.putExtra("return-data", true);
		activity.startActivityForResult(intent, MyBitmapUtil.PIC_FROM_CUTPHOTO);
		// System.out.println("getCutPhoto----cc");
	}

	/**
	 * 取出裁剪的图
	 *
	 * @throws FileNotFoundException
	 *             scale是控制大中小（总共就分为4等分，原图就不压缩，大是4分之三，中是2分之一，小是4分之一）
	 */
	public static boolean showCutPhoto(Intent data, int scale, String targetFilePath) throws FileNotFoundException {
		boolean isSuccess = false;
		if (data != null) {
			Bundle extras = data.getExtras();
			if (extras != null) {
				Bitmap cutPhoto = extras.getParcelable("data");

				if (cutPhoto != null) {
					compress50(cutPhoto);

					FileOutputStream fileOutputStream = new FileOutputStream(targetFilePath);

					BitmapFactory.Options options = new BitmapFactory.Options();
					options.inJustDecodeBounds = false;
					options.inSampleSize = scale;

					isSuccess = cutPhoto.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);// (0
				} else {
					isSuccess = false;
				}
			}
		}
		return isSuccess;
	}

	public static ByteArrayOutputStream compress50(Bitmap cutPhoto) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		cutPhoto.compress(Bitmap.CompressFormat.JPEG, 100, baos);
		// Log.v(TAG,"_baos.toByteArray().length:"+baos.toByteArray().length);
		while (baos.toByteArray().length / 1024 > 1024) {// 判断如果图片大于1M,进行压缩避免在生成图片（BitmapFactory.decodeStream）时溢出
			Log.v("compress50", "_baos.toByteArray().length:" + baos.toByteArray().length);

			baos.reset();// 重置baos即清空baos
			cutPhoto.compress(Bitmap.CompressFormat.JPEG, 50, baos);// 这里压缩50%，把压缩后的数据存放到baos中
			// Log.v(TAG,"_baos.toByteArray().length:"+baos.toByteArray().length);
		}
		return baos;
	}

}